<template>
  <div style="width: 650px">
    <el-page-header @back="$router.go(-1)" />
    <br />

    <el-card header="修改密码">
      <el-form
        ref="dataForm"
        :model="entity"
        :rules="formRules"
        label-suffix="："
        label-width="auto"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="entity.oldPassword"
            type="password"
            placeholder="请输入新密码"
            clearable
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="entity.newPassword"
            type="password"
            placeholder="请输入新密码"
            clearable
          />
        </el-form-item>
        <el-form-item label="重复新密码" prop="newPasswordCheck">
          <el-input
            v-model="entity.newPasswordCheck"
            type="password"
            placeholder="请再次输入新密码"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            class="m-auto"
            @click="submitHandler"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { putPassword } from '@/api/loginUser'

export default {
  name: 'ModifyPassword',
  data() {
    return {
      loading: false,
      entity: {},
      formRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
        ],
        newPasswordCheck: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value != this.entity.newPassword) {
                callback('新密码不匹配')
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    submitHandler() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.loading = true
          putPassword(this.entity)
            .then(() => {
              this.$message.success('修改成功')
              this.$store.commit('viewTab/DEL_VIEWTAB', this.$route.path)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
  },
}
</script>
